package cn.com.jinhao.hotline.gateway.filter;

import cn.com.jinhao.hotline.commons.base.constant.SystemConstant;
import cn.com.jinhao.hotline.commons.util.RestResponse;
import cn.com.jinhao.hotline.commons.util.MessageDigestUtils;
import cn.com.jinhao.hotline.commons.util.Algorithm;
import cn.com.jinhao.hotline.gateway.service.RedisService;
import com.alibaba.fastjson.JSON;
import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.reactivestreams.Publisher;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.context.annotation.Profile;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.core.io.buffer.DataBufferFactory;
import org.springframework.core.io.buffer.DataBufferUtils;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.http.server.reactive.ServerHttpResponseDecorator;
import org.springframework.stereotype.Component;
import org.springframework.util.MultiValueMap;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;
import java.util.*;

/**
 * 鉴权与日志统一过滤器
 *
 * @author ShaneWei
 */
@RefreshScope
@Component
@Profile(value = "prod")
public class AuthAndLogFilter implements GlobalFilter, Ordered {
    @Value("${application.app.id}")
    private String appId;

    @Value("${application.app.accessKey}")
    private String accessKey;

    @Autowired
    private RedisService redisService;

    static final Logger logger = LogManager.getLogger("request");

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {

        ServerHttpRequest serverHttpRequest = exchange.getRequest();
        ServerHttpResponse serverHttpResponse = exchange.getResponse();

        String swaggerUrl = "/v2/api-docs";
        String tokenUrl = "/token";

        if (serverHttpRequest.getURI().toString().contains(swaggerUrl) || serverHttpRequest.getURI().toString().contains(tokenUrl)) {
            return chain.filter(exchange);
        }

        List<String> auths = serverHttpRequest.getHeaders().get("AUTHORIZATION");

        StringBuilder logBuilder = new StringBuilder();
        Map<String, String> params = parseRequest(exchange, logBuilder);

        if (auths == null || auths.get(0) == null) {
            RestResponse<String> resp = new RestResponse<>(SystemConstant.ResponseCode.TOKEN_INVALID,null);
            logBuilder.append(",resp=").append(resp.toString());
            logger.info(logBuilder.toString());
            DataBuffer bodyDataBuffer = serverHttpResponse.bufferFactory().wrap(JSON.toJSONString(resp).getBytes());

            serverHttpResponse.getHeaders().add("Content-Type", "application/json;charset=UTF-8");
            return serverHttpResponse.writeWith(Flux.just(bodyDataBuffer));
        }

        if (redisService.get(auths.get(0)) == null) {
            RestResponse<String> resp = new RestResponse<>(SystemConstant.ResponseCode.TOKEN_TIMEOUT, null);
            return getVoidMono(serverHttpResponse, logBuilder, resp);
        }

        redisService.updateExpireTime(auths.get(0));
        params.put("appId", this.appId);
        params.put("accessKey", this.accessKey);

        boolean r = checkSignature(params);
        if (!r) {
            RestResponse<String> resp = new RestResponse<>(SystemConstant.ResponseCode.SIGN_INCONSISTENT, null);
            return getVoidMono(serverHttpResponse, logBuilder, resp);
        }

        DataBufferFactory bufferFactory = serverHttpResponse.bufferFactory();
        ServerHttpResponseDecorator decoratedResponse = new ServerHttpResponseDecorator(serverHttpResponse) {
            @Override
            public Mono<Void> writeWith(Publisher<? extends DataBuffer> body) {
                if (body instanceof Flux) {
                    Flux<? extends DataBuffer> fluxBody = (Flux<? extends DataBuffer>) body;
                    return super.writeWith(fluxBody.map(dataBuffer -> {
                        byte[] content = new byte[dataBuffer.readableByteCount()];
                        dataBuffer.read(content);
                        DataBufferUtils.release(dataBuffer);
                        String resp = new String(content, StandardCharsets.UTF_8);
                        logBuilder.append(",resp=").append(resp);
                        logger.info(logBuilder.toString());
                        byte[] uppedContent = new String(content, StandardCharsets.UTF_8).getBytes();
                        return bufferFactory.wrap(uppedContent);
                    }));
                }
                return super.writeWith(body);
            }
        };
        return chain.filter(exchange.mutate().response(decoratedResponse).build());
    }

    private Mono<Void> getVoidMono(ServerHttpResponse serverHttpResponse, StringBuilder logBuilder, RestResponse resp) {
        logBuilder.append(",resp=").append(resp.toString());
        logger.info(logBuilder.toString());
        DataBuffer bodyDataBuffer = serverHttpResponse.bufferFactory().wrap(JSON.toJSONString(resp).getBytes());
        serverHttpResponse.getHeaders().add("Content-Type", "application/json;charset=UTF-8");
        return serverHttpResponse.writeWith(Mono.just(bodyDataBuffer));
    }

    private Map<String, String> parseRequest(ServerWebExchange exchange, StringBuilder logBuilder) {
        ServerHttpRequest serverHttpRequest = exchange.getRequest();
        String method = serverHttpRequest.getMethodValue().toUpperCase();
        logBuilder.append(method).append(",").append(serverHttpRequest.getURI());
        MultiValueMap<String, String> query = serverHttpRequest.getQueryParams();
        Map<String, String> params = new HashMap<>(10);
        query.forEach((k, v) -> params.put(k, v.get(0)));
        if (SystemConstant.SystemConfig.POST_METHOD.getName().equals(method)) {
            String body = exchange.getAttributeOrDefault("cachedRequestBody", "");
            if (StringUtils.isNotBlank(body)) {
                logBuilder.append(",body=").append(body);
                String[] kvArray = body.split("&");
                for (String kv : kvArray) {
                    if (kv.contains("=")) {
                        String k = kv.split("=")[0];
                        String v = kv.split("=")[1];
                        if (!params.containsKey(k)) {
                            params.put(k, URLDecoder.decode(v, StandardCharsets.UTF_8));
                        }
                    }
                }
            }
        }
        return params;
    }

    private boolean checkSignature(Map<String, String> params) {
        String sign = params.get("sign");
        if (StringUtils.isBlank(sign)) {
            return false;
        }
        //检查签名
        return sign.equalsIgnoreCase(MessageDigestUtils.encrypt(MessageDigestUtils.getSignatureStr(params) + accessKey, Algorithm.MD5));
    }

    @Override
    public int getOrder() {
        return -20;
    }
}